package ru.tinkoff.decoro.demo.slice;

import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ru.tinkoff.decoro.Mask;
import ru.tinkoff.decoro.MaskDescriptor;
import ru.tinkoff.decoro.MaskImpl;
import ru.tinkoff.decoro.TextUtils;
import ru.tinkoff.decoro.demo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ru.tinkoff.decoro.slots.PredefinedSlots;
import ru.tinkoff.decoro.watchers.DescriptorFormatWatcher;

public class StaticMaskAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private static final int WIDTH = 310;
    private static final int RADIUS = 10;

    private TextField dataEdit;
    private Text maskPreviewView;
    private Text hint;
    private DescriptorFormatWatcher formatWatcher;
    private final MaskDescriptor[] maskDescriptor = new MaskDescriptor[1];
    private String textBeforeChange = "";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_static_mask);

        dataEdit = (TextField) findComponentById(ResourceTable.Id_editData);

        formatWatcher = new DescriptorFormatWatcher(MaskDescriptor.emptyMask().setTerminated(false));
        formatWatcher.installOn(dataEdit);
        hint = (Text) findComponentById(ResourceTable.Id_editHint);
        maskPreviewView = (Text) findComponentById(ResourceTable.Id_textMaskPreview);
        maskPreviewView.setText(getString(ResourceTable.String_mask_preview, ""));

        findComponentById(ResourceTable.Id_buttonMask).setClickedListener(this);

        final Mask mask = MaskImpl.createTerminated(PredefinedSlots.getRusPhoneNumber());
        mask.setPlaceholder('*');
        mask.setShowingEmptySlots(true);
        mask.insertFront("999");

        dataEdit.setFocusChangedListener(new Component.FocusChangedListener() {
            @Override
            public void onFocusChange(Component component, boolean isFocus) {
                if (isFocus) {
                    hint.setVisibility(Component.VISIBLE);
                    if (TextUtils.isEmpty(dataEdit.getText())) {
                        dataEdit.setHint("");
                    } else {
                        dataEdit.setHint(getString(ResourceTable.String_hint_data));
                    }
                } else {
                    if (TextUtils.isEmpty(dataEdit.getText())) {
                        hint.setVisibility(Component.INVISIBLE);
                        dataEdit.setHint(getString(ResourceTable.String_hint_data));
                    } else {
                        hint.setVisibility(Component.VISIBLE);
                    }
                }
            }
        });
        dataEdit.addTextObserver(new Text.TextObserver() {

            @Override
            public void onTextUpdated(String newText, int i0, int i1, int i2) {
                if (TextUtils.isEmpty(newText)) {
                    hint.setVisibility(Component.INVISIBLE);
                    dataEdit.setHint(getString(ResourceTable.String_hint_data));
                } else {
                    hint.setVisibility(Component.VISIBLE);
                    dataEdit.setHint(getString(ResourceTable.String_hint_data));
                }
                if (maskDescriptor[0] != null && textBeforeChange.length() < newText.length()) {
                    onMaskSelected(maskDescriptor[0]);
                }
                int length = maskPreviewView.getText().length() - 5;
                if (maskDescriptor[0] != null && length <= textBeforeChange.length()){
                    onMaskSelected(maskDescriptor[0]);
                }
                textBeforeChange = newText;
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        maskSelectorDialog();
    }

    private void maskSelectorDialog() {
        DirectionalLayout directionalLayout = (DirectionalLayout) LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_dialog_picker, null, false);
        CommonDialog dialog = new CommonDialog(this);
        dialog.setContentCustomComponent(directionalLayout);
        dialog.setAutoClosable(true);
        dialog.setSize(vp2px(this, WIDTH), DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        dialog.setAlignment(LayoutAlignment.CENTER);
        dialog.setCornerRadius(vp2px(this, RADIUS));
        dialog.show();
        Text customMask1 = (Text) directionalLayout.findComponentById(ResourceTable.Id_btnCustomMask1);
        customMask1.setClickedListener(v -> {
            maskDescriptor[0] = MaskDescriptor.ofSlots(PredefinedSlots.getRusPhoneNumber());
            onMaskSelected(maskDescriptor[0]);
            dialog.destroy();
        });
        Text customMask2 = (Text) directionalLayout.findComponentById(ResourceTable.Id_btnCustomMask2);
        customMask2.setClickedListener(v -> {
            maskDescriptor[0] = MaskDescriptor.ofSlots(PredefinedSlots.getCardNumberStandardMaskable());
            onMaskSelected(maskDescriptor[0]);
            dialog.destroy();
        });
        Text customMask3 = (Text) directionalLayout.findComponentById(ResourceTable.Id_btnCustomMask3);
        customMask3.setClickedListener(v -> {
            maskDescriptor[0] = MaskDescriptor.ofSlots(PredefinedSlots.getCardNumberMaestroMaskable())
                    .setTerminated(false);
            onMaskSelected(maskDescriptor[0]);
            dialog.destroy();
        });
        Text customMask4 = (Text) directionalLayout.findComponentById(ResourceTable.Id_btnCustomMask4);
        customMask4.setClickedListener(v -> {
            maskDescriptor[0] = MaskDescriptor.ofSlots(PredefinedSlots.getRusPassport());
            onMaskSelected(maskDescriptor[0]);
            dialog.destroy();
        });
    }

    private int vp2px(Context context, float vp) {
        DisplayAttributes attributes = DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes();
        return (int) (attributes.densityPixels * vp);
    }

    private void onMaskSelected(MaskDescriptor maskDescriptor) {
        formatWatcher.changeMask(maskDescriptor.setInitialValue(dataEdit.getText()));
        maskPreviewView.setText(getString(ResourceTable.String_mask_preview, maskDescriptor.toString()));
    }
}
